<template>
  <div class="user-management-container">
    <el-card class="user-management-card">
      <template #header>
        <div class="card-header">
          <span>用户管理</span>
          <div class="header-actions">
            <el-input v-model="searchQuery" placeholder="搜索用户名" style="width: 200px; margin-right: 10px;"
              clearable @clear="handleSearch" @keyup.enter="handleSearch" />
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button type="success" @click="handleAdd">新增用户</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            {{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="120" />
        <el-table-column prop="idNumber" label="身份证号" width="180" />
        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleTag(row.role)">
              {{ getRoleName(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleSetRole(row)">设置权限</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="500px">
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="userForm.sex" placeholder="请选择性别">
            <el-option label="男" value="1" />
            <el-option label="女" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idNumber">
          <el-input v-model="userForm.idNumber" placeholder="请输入身份证号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUserForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 设置权限对话框 -->
    <el-dialog v-model="roleDialogVisible" title="设置用户权限" width="400px">
      <el-form :model="roleForm" label-width="100px">
        <el-form-item label="用户名">
          <span>{{ currentUser.username }}</span>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-tag :type="getRoleTag(currentUser.role)">{{ getRoleName(currentUser.role) }}</el-tag>
        </el-form-item>
        <el-form-item label="设置角色" prop="role">
          <el-select v-model="roleForm.role" placeholder="请选择角色">
            <el-option label="普通用户" value="0" />
            <el-option label="管理员" value="1" />
            <el-option label="超级管理员" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRoleForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDateTime } from '@/utils/date'
import { getEmployeePage, addEmployee, updateEmployee, deleteEmployee, setEmployeeRole } from '@/api/employee'

const loading = ref(false)
const tableData = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 用户表单相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const userFormRef = ref()
const userForm = reactive({
  username: '',
  password: '',
  sex: '',
  phone: '',
  idNumber: ''
})

const rules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
  idNumber: [{ pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }]
})

// 角色设置相关
const roleDialogVisible = ref(false)
const currentUser = ref({})
const roleForm = reactive({
  role: ''
})

// 获取用户列表
const fetchUserList = async () => {
  loading.value = true
  try {
    const res = await getEmployeePage({
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    })
    tableData.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 角色相关方法
const getRoleName = (role) => {
  const roleMap = {
    '0': '普通用户',
    '1': '管理员',
    '2': '系统管理员'
  }
  return roleMap[role] || '未知角色'
}

const getRoleTag = (role) => {
  const tagMap = {
    '0': 'info',
    '1': 'success',
    '2': 'danger'
  }
  return tagMap[role] || ''
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUserList()
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  userForm.username = ''
  userForm.password = ''
  userForm.sex = ''
  userForm.phone = ''
  userForm.idNumber = ''
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  isEdit.value = true
  userForm.id = row.id
  userForm.username = row.username
  userForm.sex = row.sex
  userForm.phone = row.phone
  userForm.idNumber = row.idNumber
  dialogVisible.value = true
}

// 设置角色
const handleSetRole = (row) => {
  currentUser.value = row
  roleForm.role = row.role
  roleDialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteEmployee(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }).catch(() => {})
}

// 提交用户表单
const submitUserForm = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    if (isEdit.value) {
      // 编辑用户
      await updateEmployee(userForm)
      ElMessage.success('编辑成功')
    } else {
      // 新增用户
      await addEmployee(userForm)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('提交用户表单失败:', error)
    ElMessage.error('提交失败')
  }
}

// 提交角色表单
const submitRoleForm = async () => {
  try {
    await setEmployeeRole(currentUser.value.id, roleForm.role)
    ElMessage.success('设置角色成功')
    roleDialogVisible.value = false
    fetchUserList()
  } catch (error) {
    console.error('设置角色失败:', error)
    ElMessage.error('设置角色失败')
  }
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>